package com.itheima.reggie.controller;


import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//员工管理模块
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> param, HttpSession session) {
        //接受请求参数
        String username = param.get("username");
        String password = param.get("password");
        //调用service
        ResultInfo resultInfo = employeeService.login(username, password);
        //判断登陆状态
        if (resultInfo.getCode() == 1) {
            //登陆成功，将用户存储到session中
            session.setAttribute(Constant.SESSION_EMPLOYEE, resultInfo.getData());
        }
        //返回结果
        return resultInfo;
    }


    // 员工退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(HttpSession session) {
        // 1.清理session
        session.invalidate();
        // 2.返回结果
        return ResultInfo.success();
    }

    //员工列表
    @GetMapping("/employee/find")
    public ResultInfo find(String name) {

        //调用service查询
        List<Employee> list = employeeService.findList(name);
        //返回结果
        return ResultInfo.success(list);
    }

    //员工添加
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) { //接受请求参数

        //调用service方法
        employeeService.save(employee);
        //返回结果
        return ResultInfo.success();
    }

    //员工修改回显
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {//接受路径传参
        //调用service的查询
        Employee employee = employeeService.findById(id);
        //返回结果
        return ResultInfo.success(employee);
    }

    //员工修改
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){//接受参数
        //调用service修改
        employeeService.update(employee);
        //返回结果
        return ResultInfo.success();
    }
}
